package com.yuanduo_app.utils;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.drawable.Drawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.text.TextUtils;
import android.util.Base64;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.engine.Resource;
import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapResource;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.xujl.fastlib.base.BaseActivity;
import com.xujl.fastlib.utils.CollectionsUtils;
import com.xujl.fastlib.utils.LogS;
import com.xujl.fastlib.utils.StringUtils;
import com.xujl.fastlib.utils.ToastUtils;
import com.xujl.task.Emitter;
import com.xujl.task.RxExecutor;
import com.xujl.task.Task;
import com.zhongjh.albumcamerarecorder.recorder.db.RecordingItem;
import com.zhongjh.albumcamerarecorder.settings.AlbumSetting;
import com.zhongjh.albumcamerarecorder.settings.CameraSetting;
import com.zhongjh.albumcamerarecorder.settings.GlobalSetting;
import com.zhongjh.albumcamerarecorder.settings.GlobalSpec;
import com.zhongjh.albumcamerarecorder.settings.MultiMediaSetting;

import com.yuanduo_app.MainApplication;
import com.yuanduo_app.R;
import com.yuanduo_app.consts.FileConst;
import com.yuanduo_app.event.ChooseImageEvent;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import gaode.zhongjh.com.common.entity.SaveStrategy;
import gaode.zhongjh.com.common.enums.MimeType;
import gaode.zhongjh.com.common.enums.MultimediaTypes;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

import static android.app.Activity.RESULT_OK;

public class ImgHelper {
    private static final String TAG = "ImgHelper";

    public static void loadImgNormal (Context context, ImageView imageView, Object res) {
//
//        if (res instanceof String) {
//
//
//            Glide.with(context)
//                    .load(new ImgLoadEntity((String) res))
//                    .error(R.drawable.default_img_icon)
//                    .placeholder(R.drawable.default_img_icon)
//                    .fallback(R.drawable.default_img_icon)
//                    .into(imageView);
//
//            return;
//        }
        Glide.with(context)
                .load(res)
                .error(R.drawable.default_img_icon)
                .placeholder(R.drawable.default_img_icon)
                .fallback(R.drawable.default_img_icon)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imageView);
    }

    /**
     * 比例展示网络图片
     *
     * @param context
     * @param imageView
     * @param res
     */
    public static void loadImgScale (Context context, ImageView imageView, Object res) {
        Glide.with(context)
                .load(res)
                .dontTransform()
                .error(R.drawable.default_img_icon)
                .placeholder(R.drawable.default_img_icon)
                .fallback(R.drawable.default_img_icon)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed (@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady (Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        imageView.setAdjustViewBounds(true);
                        imageView.setImageDrawable(resource);
                        return true;
                    }
                })
                .into(imageView);
    }

    /**
     * 原尺寸加载
     *
     * @param context
     * @param imageView
     * @param res
     */
    public static void loadImgSourceSize (Context context, ImageView imageView, Object res) {
        RequestOptions options = new RequestOptions()
                .override(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
        int widthPixels = context.getResources().getDisplayMetrics().widthPixels;

        float per = widthPixels / 750.0f;
        Glide.with(context)
                .load(res)
                .error(R.drawable.default_img_icon)
                .placeholder(R.drawable.default_img_icon)
                .fallback(R.drawable.default_img_icon)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .apply(options).
                listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed (@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady (Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        try {
                            ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
                            layoutParams.width = (int) (per * resource.getMinimumWidth());
                            layoutParams.height = (int) (per * resource.getMinimumHeight());
                            imageView.setLayoutParams(layoutParams);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        return false;
                    }
                })
                .into(imageView);
    }

    /**
     * 加载圆角矩形
     *
     * @param context
     * @param imageView
     * @param res
     */
    public static void loadCornersImg (Context context, ImageView imageView, Object res, float radius) {
        RoundedCornersTransform transform = new RoundedCornersTransform(context, radius);
        transform.setNeedCorner(true, true, true, true);
        RequestOptions options = new RequestOptions().transform(transform);
        Glide.with(context).load(res)
                .error(R.drawable.default_img_icon)
                .placeholder(R.drawable.default_img_icon)
                .fallback(R.drawable.default_img_icon)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .apply(options)
                .into(imageView);
    }


    /**
     * 加载圆形头像图片
     *
     * @param context
     * @param imageView
     * @param res
     */
    public static void loadHeadCircleImg (Context context, ImageView imageView, Object res) {
        Glide.with(context).load(res)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .error(R.drawable.default_img_icon)
                .placeholder(R.drawable.default_img_icon)
                .fallback(R.drawable.default_img_icon)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imageView);
    }

    /**
     * 加载圆形图片
     *
     * @param context
     * @param imageView
     * @param res
     */
    public static void loadCircleImg (Context context, ImageView imageView, Object res) {
        Glide.with(context).load(res)
                .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                .error(R.drawable.default_img_icon)
                .placeholder(R.drawable.default_img_icon)
                .fallback(R.drawable.default_img_icon)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(imageView);
    }

    public static Bitmap getUrlImage (Context context, Object url) {
        FutureTarget<Bitmap> bitmap = Glide.with(context)
                .asBitmap()
                .load(url)
                .submit();
        try {
            return bitmap.get();
        } catch (ExecutionException e) {
            e.printStackTrace();
            return null;
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void setRvScrollPauseLoading (RecyclerView recyclerView) {
        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged (RecyclerView recyclerView, int newState) {
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    Glide.with(recyclerView.getContext()).resumeRequests();
                } else {
                    Glide.with(recyclerView.getContext()).pauseRequests();
                }
            }

            @Override
            public void onScrolled (@NonNull RecyclerView recyclerView, int dx, int dy) {
                if (Math.abs(dy) < 20) {
                    Glide.with(recyclerView.getContext()).resumeRequests();
                } else {
                    Glide.with(recyclerView.getContext()).pauseRequests();
                }
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    /**
     * @author csc
     * @date 2019-01-18
     * Todo 设置图片部分圆角
     */
    public static class RoundedCornersTransform implements Transformation<Bitmap> {
        private BitmapPool mBitmapPool;

        private float radius;

        private boolean isLeftTop, isRightTop, isLeftBottom, isRightBotoom;

        /**
         * 需要设置圆角的部分
         *
         * @param leftTop     左上角
         * @param rightTop    右上角
         * @param leftBottom  左下角
         * @param rightBottom 右下角
         */
        public void setNeedCorner (boolean leftTop, boolean rightTop, boolean leftBottom, boolean rightBottom) {
            isLeftTop = leftTop;
            isRightTop = rightTop;
            isLeftBottom = leftBottom;
            isRightBotoom = rightBottom;
        }

        /**
         * @param context 上下文
         * @param radius  圆角幅度
         */
        public RoundedCornersTransform (Context context, float radius) {
            this.mBitmapPool = Glide.get(context).getBitmapPool();
            this.radius = radius;
        }

        @NonNull
        @Override
        public Resource<Bitmap> transform (@NonNull Context context, @NonNull Resource<Bitmap> resource, int outWidth, int outHeight) {

            Bitmap source = resource.get();
            int finalWidth, finalHeight;
            //输出目标的宽高或高宽比例
            float scale;
            if (outWidth > outHeight) {
                //如果 输出宽度 > 输出高度 求高宽比

                scale = (float) outHeight / (float) outWidth;
                finalWidth = source.getWidth();
                //固定原图宽度,求最终高度
                finalHeight = (int) ((float) source.getWidth() * scale);
                if (finalHeight > source.getHeight()) {
                    //如果 求出的最终高度 > 原图高度 求宽高比

                    scale = (float) outWidth / (float) outHeight;
                    finalHeight = source.getHeight();
                    //固定原图高度,求最终宽度
                    finalWidth = (int) ((float) source.getHeight() * scale);
                }
            } else if (outWidth < outHeight) {
                //如果 输出宽度 < 输出高度 求宽高比

                scale = (float) outWidth / (float) outHeight;
                finalHeight = source.getHeight();
                //固定原图高度,求最终宽度
                finalWidth = (int) ((float) source.getHeight() * scale);
                if (finalWidth > source.getWidth()) {
                    //如果 求出的最终宽度 > 原图宽度 求高宽比

                    scale = (float) outHeight / (float) outWidth;
                    finalWidth = source.getWidth();
                    finalHeight = (int) ((float) source.getWidth() * scale);
                }
            } else {
                //如果 输出宽度=输出高度
                finalHeight = source.getHeight();
                finalWidth = finalHeight;
            }

            //修正圆角
            this.radius *= (float) finalHeight / (float) outHeight;
            Bitmap outBitmap = this.mBitmapPool.get(finalWidth, finalHeight, Bitmap.Config.ARGB_8888);
            if (outBitmap == null) {
                outBitmap = Bitmap.createBitmap(finalWidth, finalHeight, Bitmap.Config.ARGB_8888);
            }

            Canvas canvas = new Canvas(outBitmap);
            Paint paint = new Paint();
            //关联画笔绘制的原图bitmap
            BitmapShader shader = new BitmapShader(source, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            //计算中心位置,进行偏移
            int width = (source.getWidth() - finalWidth) / 2;
            int height = (source.getHeight() - finalHeight) / 2;
            if (width != 0 || height != 0) {
                Matrix matrix = new Matrix();
                matrix.setTranslate((float) (-width), (float) (-height));
                shader.setLocalMatrix(matrix);
            }

            paint.setShader(shader);
            paint.setAntiAlias(true);
            RectF rectF = new RectF(0.0F, 0.0F, (float) canvas.getWidth(), (float) canvas.getHeight());
            //先绘制圆角矩形
            canvas.drawRoundRect(rectF, this.radius, this.radius, paint);

            //左上角圆角
            if (!isLeftTop) {
                canvas.drawRect(0, 0, radius, radius, paint);
            }
            //右上角圆角
            if (!isRightTop) {
                canvas.drawRect(canvas.getWidth() - radius, 0, canvas.getWidth(), radius, paint);
            }
            //左下角圆角
            if (!isLeftBottom) {
                canvas.drawRect(0, canvas.getHeight() - radius, radius, canvas.getHeight(), paint);
            }
            //右下角圆角
            if (!isRightBotoom) {
                canvas.drawRect(canvas.getWidth() - radius, canvas.getHeight() - radius, canvas.getWidth(), canvas.getHeight(), paint);
            }

            return BitmapResource.obtain(outBitmap, this.mBitmapPool);
        }


        @Override
        public void updateDiskCacheKey (@NonNull MessageDigest messageDigest) {
        }
    }

    /**
     * 将相册选择的数据转化成真实图片路径
     *
     * @param context
     * @param uri
     * @return
     */
    public static String getRealFilePath (Context context, Uri uri) {

        if (null == uri) return null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return getFilePathForN(context, uri);
        }
        final String scheme = uri.getScheme();
        String realPath = null;
        if (scheme == null)
            realPath = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            realPath = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA},
                    null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        realPath = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        if (TextUtils.isEmpty(realPath)) {
            if (uri != null) {
                String uriString = uri.toString();
                int index = uriString.lastIndexOf("/");
                String imageName = uriString.substring(index);
                File storageDir;

                storageDir = Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES);
                File file = new File(storageDir, imageName);
                if (file.exists()) {
                    realPath = file.getAbsolutePath();
                } else {
                    storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
                    File file1 = new File(storageDir, imageName);
                    realPath = file1.getAbsolutePath();
                }
            }
        }
        return realPath;
    }

    /**
     * android7.0以上处理方法
     */
    private static String getFilePathForN (Context context, Uri uri) {
        try {
            Cursor returnCursor = context.getContentResolver().query(uri, null, null, null, null);
            int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
            returnCursor.moveToFirst();
            String name = (returnCursor.getString(nameIndex));
            File file = new File(context.getFilesDir(), name);
            InputStream inputStream = context.getContentResolver().openInputStream(uri);
            FileOutputStream outputStream = new FileOutputStream(file);
            int read = 0;
            int maxBufferSize = 1 * 1024 * 1024;
            int bytesAvailable = inputStream.available();

            int bufferSize = Math.min(bytesAvailable, maxBufferSize);

            final byte[] buffers = new byte[bufferSize];
            while ((read = inputStream.read(buffers)) != -1) {
                outputStream.write(buffers, 0, read);
            }
            returnCursor.close();
            inputStream.close();
            outputStream.close();
            return file.getPath();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static final int REQUEST_CODE_CHOOSE = 9;

    public static void openGallery (Activity activity, int requestCode) {
        // 相册
        AlbumSetting albumSetting = new AlbumSetting(true)
                .mimeTypeSet(MimeType.ofImage())// 支持的类型：图片，视频
                .countable(true)// 是否显示多选图片的数字
                .originalEnable(true)// 开启原图
                .maxOriginalSize(1); // 最大原图size,仅当originalEnable为true的时候才有效
        // 拍摄有关设置
        CameraSetting cameraSetting = new CameraSetting();
        cameraSetting.mimeTypeSet(MimeType.ofImage());// 支持的类型：图片，视频
        // 全局
        GlobalSetting globalSetting = MultiMediaSetting.from(activity).choose(MimeType.ofAll());

        // 开启相册功能
        globalSetting.albumSetting(albumSetting);
        globalSetting.theme(R.style.AppTheme_Blue);
        // 开启拍摄功能
        globalSetting.cameraSetting(cameraSetting);
        GlobalSpec.getInstance().isImageEdit = false;
        globalSetting
                .setOnMainListener(errorMessage -> ToastUtils.toast(errorMessage))
                .allStrategy(new SaveStrategy(true, FileConst.fileProvider, "img"))// 设置路径和7.0保护路径等等
                .imageEngine(new Glide4Engine())    // for glide-V4
                .maxSelectablePerMediaType(1, 0, 0)// 最大10张图片或者最大1个视频
                .forResult(requestCode);
//        openGallery(activity, REQUEST_CODE_CHOOSE);
    }

    public static void openGalleryAndVideo (Activity activity) {
        // 拍摄有关设置
        CameraSetting cameraSetting = new CameraSetting();
        cameraSetting.mimeTypeSet(MimeType.ofAll());// 支持的类型：图片，视频
        // 相册
        AlbumSetting albumSetting = new AlbumSetting(true)
                .mimeTypeSet(MimeType.ofAll())// 支持的类型：图片，视频
                .countable(true)// 是否显示多选图片的数字
                .originalEnable(true)// 开启原图
                .maxOriginalSize(1); // 最大原图size,仅当originalEnable为true的时候才有效
        // 全局
        GlobalSetting globalSetting = MultiMediaSetting.from(activity).choose(MimeType.ofAll());

        // 开启相册功能
        globalSetting.albumSetting(albumSetting);
        // 开启拍摄功能
        globalSetting.cameraSetting(cameraSetting);
        globalSetting.theme(R.style.AppTheme_Blue);
        GlobalSpec.getInstance().isImageEdit = false;
        globalSetting
                .setOnMainListener(errorMessage -> ToastUtils.toast(errorMessage))
                .allStrategy(new SaveStrategy(true, FileConst.fileProvider, "img"))// 设置路径和7.0保护路径等等
                .imageEngine(new Glide4Engine())    // for glide-V4
                .maxSelectablePerMediaType(1, 1, 0)// 最大10张图片或者最大1个视频
                .forResult(REQUEST_CODE_CHOOSE);
//        openGallery(activity, REQUEST_CODE_CHOOSE);
    }


    public static void receiveImageOrVideo (ChooseImageEvent event, int requestCode, int resultCode, Intent data, BaseActivity activity, CompressImageCallback callback) {
        if (resultCode != RESULT_OK)
            return;
        switch (requestCode) {
            case REQUEST_CODE_CHOOSE:
                // 获取类型，根据类型设置不同的事情
                switch (MultiMediaSetting.obtainMultimediaType(data)) {
                    case MultimediaTypes.PICTURE:
                        // 图片
                        List<String> path = MultiMediaSetting.obtainPathResult(data);
                        RxExecutor.getInstance()
                                .executeTask(new Task<String>() {
                                    @Override
                                    public void run (Emitter<String> emitter) throws Exception {
                                        super.run(emitter);
                                        LogS.e(TAG, "图片path:" + path.get(0));
//                        String realFilePath = getRealFilePath(MainApplication.getApplication(), resultPhotos.get(0).uri);
                                        String realFilePath = path.get(0);
                                        if (StringUtils.isEmpty(realFilePath)) {
                                            LogS.e(TAG, "图片转换路径获取失败");
                                            return;
                                        }
                                        LogS.e(TAG, "转换后路径：" + realFilePath);
                                        final File root = new File(FileConst.PHOTO_DIR);
                                        if (!root.exists()) {
                                            final boolean mkdirs = root.mkdirs();
                                            LogS.e(TAG, "压缩路径不存在，创建：" + mkdirs);
                                        }
                                        emitter.next(realFilePath);
                                    }

                                    @Override
                                    public void onNext (String realFilePath) {
                                        super.onNext(realFilePath);
                                        Luban.with(MainApplication.getApplication())
                                                .load(realFilePath)
                                                .ignoreBy(100)
                                                .setTargetDir(FileConst.PHOTO_DIR)
                                                .filter(path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")))
                                                .setCompressListener(new OnCompressListener() {
                                                    @Override
                                                    public void onStart () {
                                                        // 压缩开始前调用，可以在方法内启动 loading UI
                                                        activity.exposeView().showLoadingWindow();
                                                    }

                                                    @Override
                                                    public void onSuccess (File file) {
                                                        RxExecutor.getInstance()
                                                                .executeTask(new Task<String>() {
                                                                    @Override
                                                                    public void run (Emitter<String> emitter) throws Exception {
                                                                        super.run(emitter);
                                                                        emitter.next(getBase64StringFromFile(file.getAbsolutePath()));
                                                                    }

                                                                    @Override
                                                                    public void onNext (String data) {
                                                                        super.onNext(data);
                                                                        //  压缩成功后调用，返回压缩后的图片文件
                                                                        if (callback != null) {
                                                                            callback.onCompressComplete(file, data, false);
                                                                        }
                                                                    }

                                                                    @Override
                                                                    public void onFinished () {
                                                                        super.onFinished();
                                                                        activity.exposeView().dismissLoadingWindow();
                                                                    }
                                                                });

                                                    }

                                                    @Override
                                                    public void onError (Throwable e) {
                                                        //  当压缩过程出现问题时调用
                                                        activity.exposeView().dismissLoadingWindow();
                                                        e.printStackTrace();
                                                        ToastUtils.toast("图片压缩失败");
                                                    }
                                                }).launch();
                                    }
                                });
                        break;
                    case MultimediaTypes.VIDEO:
                        // 录像
                        List<String> videoPaths = MultiMediaSetting.obtainPathResult(data);
                        final String videoPath = videoPaths.get(0);
                        RxExecutor.getInstance()
                                .executeTask(new Task<String>() {
                                    @Override
                                    public void run (Emitter<String> emitter) throws Exception {
                                        super.run(emitter);
                                        emitter.next(bitmapToBase64(getVideoThumb(videoPath)));
                                    }

                                    @Override
                                    public void onNext (String data) {
                                        super.onNext(data);
                                        //  压缩成功后调用，返回压缩后的图片文件
                                        if (callback != null) {
                                            callback.onCompressComplete(new File(videoPath), data, true);
                                        }
                                    }

                                    @Override
                                    public void onFinished () {
                                        super.onFinished();
                                        activity.exposeView().dismissLoadingWindow();
                                    }
                                });
                        break;
                    case MultimediaTypes.AUDIO:
                        // 语音
                        RecordingItem recordingItem = MultiMediaSetting.obtainRecordingItemResult(data);
//                        mBinding.mplImageList.addAudioStartUpload(recordingItem.getFilePath(), recordingItem.getLength());
                        break;
                    case MultimediaTypes.BLEND:
                        // 混合类型，意思是图片可能跟录像在一起.
//                        mBinding.mplImageList.addImagesStartUpload(MultiMediaSetting.obtainPathResult(data));
                        break;
                }
                break;
        }
    }

    /**
     * 获取视频文件截图
     *
     * @param path 视频文件的路径
     * @return Bitmap 返回获取的Bitmap
     */

    public static Bitmap getVideoThumb (String path) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);
        return media.getFrameAtTime();
    }


    public static void receiveImageAndCompress (ChooseImageEvent event, int requestCode, int resultCode, Intent data, BaseActivity activity, CompressImageCallback callback) {
        if (requestCode != REQUEST_CODE_CHOOSE || resultCode != RESULT_OK) {
            LogS.e(TAG, "未选获取到图片选中信息");
            return;
        }
        ArrayList<Photo> resultPhotos = data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS);

        if (CollectionsUtils.isEmpty(resultPhotos)) {
            LogS.e(TAG, "未选中图片");
            return;
        }
        if (StringUtils.startWith(resultPhotos.get(0).type, "video/")) {
            //  压缩成功后调用，返回压缩后的图片文件
            if (callback != null) {
                callback.onCompressComplete(new File(resultPhotos.get(0).path), "", false);
            }
            return;
        }
        if (event != null && StringUtils.equals("faceCer", event.getType()) &&
                StringUtils.endWith(resultPhotos.get(0).path, ".png")) {
            ToastUtils.toast("图片格式仅支持.jpg格式，请重新上传");
            return;
        }
        RxExecutor.getInstance()
                .executeTask(new Task<String>() {
                    @Override
                    public void run (Emitter<String> emitter) throws Exception {
                        super.run(emitter);
                        LogS.e(TAG, "图片path:" + resultPhotos.get(0).path);
//                        String realFilePath = getRealFilePath(MainApplication.getApplication(), resultPhotos.get(0).uri);
                        String realFilePath = resultPhotos.get(0).path;
                        if (StringUtils.isEmpty(realFilePath)) {
                            LogS.e(TAG, "图片转换路径获取失败");
                            return;
                        }
                        LogS.e(TAG, "转换后路径：" + realFilePath);
                        final File root = new File(FileConst.PHOTO_DIR);
                        if (!root.exists()) {
                            final boolean mkdirs = root.mkdirs();
                            LogS.e(TAG, "压缩路径不存在，创建：" + mkdirs);
                        }
                        emitter.next(realFilePath);
                    }

                    @Override
                    public void onNext (String realFilePath) {
                        super.onNext(realFilePath);
                        Luban.with(MainApplication.getApplication())
                                .load(realFilePath)
                                .ignoreBy(100)
                                .setTargetDir(FileConst.PHOTO_DIR)
                                .filter(path -> !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif")))
                                .setCompressListener(new OnCompressListener() {
                                    @Override
                                    public void onStart () {
                                        // 压缩开始前调用，可以在方法内启动 loading UI
                                        activity.exposeView().showLoadingWindow();
                                    }

                                    @Override
                                    public void onSuccess (File file) {
                                        RxExecutor.getInstance()
                                                .executeTask(new Task<String>() {
                                                    @Override
                                                    public void run (Emitter<String> emitter) throws Exception {
                                                        super.run(emitter);
                                                        emitter.next(getBase64StringFromFile(file.getAbsolutePath()));
                                                    }

                                                    @Override
                                                    public void onNext (String data) {
                                                        super.onNext(data);
                                                        //  压缩成功后调用，返回压缩后的图片文件
                                                        if (callback != null) {
                                                            callback.onCompressComplete(file, data, false);
                                                        }
                                                    }

                                                    @Override
                                                    public void onFinished () {
                                                        super.onFinished();
                                                        activity.exposeView().dismissLoadingWindow();
                                                    }
                                                });

                                    }

                                    @Override
                                    public void onError (Throwable e) {
                                        //  当压缩过程出现问题时调用
                                        activity.exposeView().dismissLoadingWindow();
                                        e.printStackTrace();
                                        ToastUtils.toast("图片压缩失败");
                                    }
                                }).launch();
                    }
                });


    }

    public static String getBase64StringFromFile (String absoluteFilePath) {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(new File(absoluteFilePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        byte[] bytes;
        byte[] buffer = new byte[8192];
        int bytesRead;
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        bytes = output.toByteArray();
        return Base64.encodeToString(bytes, Base64.NO_WRAP);
    }

    /* * bitmap转base64
     * */
    private static String bitmapToBase64 (Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * Gets the content:// URI from the given corresponding path to a file
     *
     * @param context
     * @param imageFile
     * @return content Uri
     */
    public static Uri getImageContentUri (Context context, File imageFile) {
        String filePath = imageFile.getAbsolutePath();
        Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[]{MediaStore.Images.Media._ID}, MediaStore.Images.Media.DATA + "=? ",
                new String[]{filePath}, null);
        if (cursor != null && cursor.moveToFirst()) {
            int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
            Uri baseUri = Uri.parse("content://media/external/images/media");
            return Uri.withAppendedPath(baseUri, "" + id);
        } else {
            if (imageFile.exists()) {
                ContentValues values = new ContentValues();
                values.put(MediaStore.Images.Media.DATA, filePath);
                return context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } else {
                return null;
            }
        }
    }

    public interface CompressImageCallback {
        void onCompressComplete (File file, String base64, boolean isVideo);
    }
}
